package com.hpradip.android.accessNumberSpeedDialer;

import java.util.List;

import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ListView;

public class AccessNumberSpeedDialerActivity extends ListActivity implements
		OnSharedPreferenceChangeListener {

	public static final String TAG = "VonageSpeedDialer";
	private static final int AGREEMENT_REQUEST = 111;
	/** Called when the activity is first created. */

	ContactsAdapter contactsAdapter;
	private static SharedPreferences preferences;
	private GoogleAnalyticsTracker tracker;
	private final int APP_EXIT_DIALOG = 1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		showEULA();

		preferences = PreferenceManager.getDefaultSharedPreferences(this);
		preferences.registerOnSharedPreferenceChangeListener(this);

		tracker = GoogleAnalyticsTracker.getInstance();
		tracker.setAnonymizeIp(true);
		tracker.startNewSession(getResources().getString(R.string.analytics_tracking_code),5,this);
		
		loadAllContacts();

		populateDefultSettings();
		setOnClickListener();
	}

	private void showEULA() {
		SharedPreferences preferences = getSharedPreferences(getResources().getString(R.string.EULA_preferences_key), Activity.MODE_PRIVATE);
		 if (!preferences.getBoolean(getResources().getString(R.string.EULA_accepted_key), false)) {
		 Intent intent = new Intent(this,EULAActivity.class);
		 startActivityForResult(intent, AGREEMENT_REQUEST);
		 }
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case AGREEMENT_REQUEST:
			if(resultCode==RESULT_CANCELED)
				{
				Builder builder = new AlertDialog.Builder(this);
				builder.setIcon(android.R.drawable.ic_dialog_alert);
				builder.setMessage(getResources().getString(R.string.app_exit_message));
				builder.setTitle(getResources().getString(R.string.app_exit_title));
				builder.setPositiveButton("OK",new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						android.os.Process.killProcess(android.os.Process.myPid());
					}
				});
				
				builder.setCancelable(false);
				builder.create().show();
				}else
			if(resultCode==RESULT_OK)
			{
				SharedPreferences preferences = getSharedPreferences(getResources().getString(R.string.EULA_preferences_key), Activity.MODE_PRIVATE);
				 preferences.edit().putBoolean(getResources().getString(R.string.EULA_accepted_key), true).commit();
			}
			else
				finish();

		default:
			break;
		}
	}

	private void loadAllContacts() {
		List<Contact> contacts = new ContactsProvider().loadContacts(this);
		contactsAdapter = new ContactsAdapter(this,
				R.layout.contacts_list_item, contacts);
		setListAdapter(contactsAdapter);
	}

	private void setOnClickListener() {
		ImageButton settings_btn = (ImageButton) findViewById(R.id.menu_settings);
		settings_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showPreferences(AccessNumberSpeedDialerActivity.this);
			}
		});

		ImageButton help_btn = (ImageButton) findViewById(R.id.menu_help);
		help_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showHelp(AccessNumberSpeedDialerActivity.this);
			}
		});

		ImageButton search_btn = (ImageButton) findViewById(R.id.menu_search);
		search_btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onSearchRequested();
			}
		});
	}

	private void populateDefultSettings() {
		if (preferences.getString(
				getResources().getString(R.string.key_default_contacts_view),
				null) == null) {
			String[] display_options = getResources().getStringArray(
					R.array.contacts_display_options_values);
			preferences
					.edit()
					.putString(
							getResources().getString(
									R.string.key_default_contacts_view),
							display_options[1]).commit();
		}

		String default_isd_code = preferences.getString(getResources()
				.getString(R.string.default_isd_code), null);
		if (default_isd_code == null || default_isd_code.length() == 0) {

			preferences
					.edit()
					.putString(
							getResources().getString(
									R.string.international_dial_code),
							getResources().getString(R.string.default_isd_code))
					.commit();
		}
	}

	// private List<Contact> getDummyData() {
	// List<Contact> contacts = new ArrayList<Contact>();
	//
	// for (int i = 0; i < 5; i++) {
	// Contact contact = new Contact();
	// contact.setId(i);
	// contact.setName("Pradip Hudekar");
	// contact.setNumber("+1-732-476-4543");
	// contact.setTimesCalled(10);
	// contacts.add(contact);
	// }
	// return contacts;
	// }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_settings:
			showPreferences(this);
			break;

		case R.id.menu_dialpad:
			showDialpad(this);
			break;

		case R.id.menu_help:
			showHelp(this);
			break;

		case R.id.menu_search:
			onSearchRequested();
			break;
		}
		return true;
	}

	public static void showHelp(Context context) {
		Intent helpIntent = new Intent(context, HelpActivity.class);
		context.startActivity(helpIntent);
	}

	public static void showDialpad(Context context) {
		Intent intent = new Intent(context, DialpadActivity.class);
		context.startActivity(intent);
	}

	public static void showPreferences(Context context) {
		Intent i = new Intent(context, DialerPreferencesActivity.class);
		context.startActivity(i);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		
		 tracker.trackEvent(
		            "UserActions",  // Category
		            "Call",  // Action
		            "total", // Label
		            1);       // Value

		Contact contact = contactsAdapter.getItem(position);
		String number = contact.getNumber();
		if (contact == null || number == null)
			return;
		dialNumber(this,contact.getId(),number,tracker);
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
		preferences = arg0;
		loadAllContacts();
	}

	@Override
	protected void onResume() {
		tracker.trackPageView("/" + this.getClass().getSimpleName());
		loadAllContacts();
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		tracker.dispatch();
	}

	public static void dialNumber(Context context, int contactId,
			String number, GoogleAnalyticsTracker tracker) {
		
		Resources resources = context.getResources();

		String accessNumber = preferences.getString(
				resources.getString(R.string.key_access_number), null);

		String passcode = preferences.getString(
				resources.getString(R.string.key_pin), null);

		String isdCode = preferences.getString(
				resources.getString(R.string.international_dial_code), resources.getString(R.string.default_international_dial_code));
		
		String pauseCharacter = preferences.getString(
				resources.getString(R.string.pause_character), resources.getString(R.string.default_pause_character));

		TelephoneUtils.dialNumber(context, contactId, number, accessNumber,
				passcode, isdCode,pauseCharacter,tracker);
	}

}